using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace PS.Tools.SiteBuilder.Features
{
#if !SANDBOX
    class SPRequestWrapper
    {
        object _request;
        SPWeb _web;
        Type _tSPRequest;

        public SPRequestWrapper(SPWeb web)
        {
            _web = web;
            _request = GetRequest(web);
            _tSPRequest = _request.GetType();
        }

        private object GetRequest(SPWeb web)
        {
            Type tWeb = typeof(SPWeb);
            PropertyInfo piRequest = tWeb.GetProperty("Request", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreReturn);
            MethodInfo miGetRequest = piRequest.GetGetMethod(true);
            return miGetRequest.Invoke(web, null);
        }

        public void ApplyViewToListWebPart(string bstrWebUrl, string bstrWebPartID,
                                           string bstrListID, string bstrViewID,
                                           uint dwToolbarSettings, out uint pdwFlags)
        {
            pdwFlags = 0;

            MethodInfo method =
                _tSPRequest.GetMethod("ApplyViewToListWebPart", BindingFlags.Public | BindingFlags.Instance);
            // ,null, new Type[] {typeof(string), typeof(string), typeof(string), typeof(string), typeof(uint), typeof(uint)},
            // null);
            try
            {
                object[] args = new object[]
                    {
                        bstrWebUrl, bstrWebPartID, bstrListID, bstrViewID,
                        dwToolbarSettings, null
                    };
                method.Invoke(_request, args);
            }
            catch (Exception e)
            {
                throw new WebPartPageUserException(e.Message, e.InnerException);
            }
        }
    }
#endif
}
